let app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //地址
    address: {

//       address: "民族大道1号"
// city_id: 233
// city_name: "深圳市"
// country_id: 1
// district_id: 2414
// district_name: "南山区"
// full_region: "广东省深圳市南山区"
// id: 3
// is_default: 1
// mobile: "13800008888"
// name: "小明"
// province_id: 20
// province_name: "广东省"
// user_id: 1

country_id: 1,
      id: 0,
      name: '',
      mobile: '',
      province_id: 2,//省份id
      province_name: '北京',
      city_id: 37,//城市id
      city_name: '北京',
      district_id: 403,//区id
      district_name: '东城区',
      full_region:'',
      address: '',//街道地址详情
      is_default: false
    },   //收货地址对象
    //省市区数组
    provinces: [],//所有省份
    cities: [],//当前所有城市
    areas: [],//当前所有小区
    PCA: '',
    showDialog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log("地址id-----", options.id);
    let id = 'address.id';
    if (options.id) {
      this.setData({
        [id]: options.id
      });
      this.getOneAdd(options.id);
    }
    console.log("地址id",this.data.address.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //监听收货人姓名的值
  getAddName: function (e) {
    let name = 'address.name'
    let newname = e.detail.value;

    this.setData({
      // wCount:message.length,    //实时监听留言的长度
      [name]: newname   //实时监听留言的内容,并记录在data中
    });
    console.log(name)
    console.log("data中的姓名", this.data.address.name);
  },
  //监听收货人手机的值
  getAddMobile: function (e) {
    let mobile = 'address.mobile'
    let newmobile = e.detail.value;
    // console.log(name)
    this.setData({
      // wCount:message.length,    //实时监听留言的长度
      [mobile]: newmobile   //实时监听留言的内容,并记录在data中
    });
    // console.log("data中的手机",this.data.address.mobile);
  },
  //监听收货人详细街道的值
  getAddStreet: function (e) {
    let address = 'address.address';
    let newaddress = e.detail.value;
    // console.log(name)
    this.setData({
      // wCount:message.length,    //实时监听留言的长度
      [address]: newaddress   //实时监听留言的内容,并记录在data中
    });
    // console.log("data中的详细地址",this.data.address.address);
  },
  //取消按钮跳转会列表页
  cancelAddress() {
    wx.navigateTo({
      url: '/pages/personal/address/address',
    })
  },
  //保存按钮事件
  saveAddress() {

    let reg = /^[\u2E80-\u9FFF]+$/;//定义中文正则表达式
    let name = this.data.address.name;//获取地址中的姓名的值
    let mobile = this.data.address.mobile;//获取地址中的电话的值
    let pca = this.data.address.full_region;//获取省市区的值
    let street = this.data.address.address;//获取地知道红的详细街道的值

    if ((name == '') || (mobile == '') || (pca == '') || (street == '')) {
      wx.showToast({
        title: '请填写完整的地址',
        icon: 'none'
      })
      return;
    } else if (!reg.test(name)) {
      wx.showToast({
        title: '姓名只能为中文',
        icon: 'none'
      })
      return;
    } else if (!(/^1[3456789]\d{9}$/.test(mobile))) {
      wx.showToast({
        title: '手机号码格式不对',
        icon: 'none'
      })
      return;
    }
    console.log(this.data.address);//测试data中的address是否为空
    let id = this.data.address.id;
    if(id == 0){
      wx.request({
        url: app.globalData.api.AddAddress,
        method: 'POST',
        data: {
          address: this.data.address.address,
          city_id: this.data.address.city_id,
          district_id: this.data.address.district_id,
          is_default: this.data.address.is_default,
          mobile: this.data.address.mobile,
          name: this.data.address.name,
          province_id: this.data.address.province_id,
          id: this.data.address.id,
        },
        header: {
          "content-type": "application/json",
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: (res) => {
          console.log("添加地址", res);
          //成功保存后跳转到列表页
          if (res.data.errno === 0) {
            wx.navigateTo({
              url: '/pages/personal/address/address',
            })
          }
        }
  
      })
    }else{
      wx.request({
        url: app.globalData.api.AddAddress,
        method: 'POST',
        data: {
          address: this.data.address.address,
          city_id: this.data.address.city_id,
          district_id: this.data.address.district_id,
          is_default: this.data.address.is_default,
          mobile: this.data.address.mobile,
          name: this.data.address.name,
          province_id: this.data.address.province_id,
          id: this.data.address.id,
        },
        header: {
          "content-type": "application/json",
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: (res) => {
          console.log("修改地址", res);
          //成功保存后跳转到列表页
          if (res.data.errno === 0) {
            wx.navigateTo({
              url: '/pages/personal/address/address',
            })
          }
        }
  
      })
    }
    
  },
  // 修改默认选项
  changIsDefault(e) {
    // console.log(e);
    let def = 'address.is_default';
    // let defau = this.data.address.is_default;
    this.setData({
      [def]: this.data.address.is_default == true ? false : true
    });
    console.log(this.data.address.is_default);
  },

  //监听省市区的值变化
  bindChange(e) {
    const val = e.detail.value
    console.log(val)
    //把省市区各自的id记录在data中
    let newprovince_id = 'address.province_id';
    let c_id = 'address.city_id';
    let newdistrict_id = 'address.district_id';
    let province = 'address.province_name';
    let city = 'address.city_name';
    let district = 'address.district_name';

    let preprovince_id = this.data.address.province_id;//获取当前省份id
    console.log("bindchange前省份id", preprovince_id);

    let precity_id = this.data.address.city_id;//获取当前城市id
    console.log("bindchange前城市id", precity_id);

    this.setData({
      //修改当前选中的省市区的对应id和名字
      [newprovince_id]: this.data.provinces[val[0]].id, //获取当前省份id
      [c_id]: this.data.cities[val[1]].id,              //获取当前城市id
      [newdistrict_id]: this.data.areas[val[2]].id,     //获取当前小区id

      [province]: this.data.provinces[val[0]].name,  //获取当前省份名字
      [city]: this.data.cities[val[1]].name,        //获取当前城市名字
      [district]: this.data.areas[val[2]].name,     //获取当前小区的名字
    })

    // 省份变了重新查询城市数据
    if (preprovince_id !== this.data.address.province_id) {
      let newprovince_id1 = this.data.address.province_id;
      this.pickCity(newprovince_id1);
      console.log("bindchange重新查询城市：当前省份id：", this.data.address.province_id);
    }

    //如果城市变了重新查询小区数据
    if (precity_id !== this.data.address.city_id) {
      this.pickArea(this.data.address.city_id);
      console.log("bindchange重新查询小区：当前城市id：", this.data.address.city_id);
    }
  },
  // 查询省份
  pickProvince() {
    wx.request({
      url: 'https://nideshop.ttxtouring.com/api/region/list?parentId=1',
      header: {
        "content-type": "application/json",
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      success: (res) => {

        let province = res.data.data;//获取到的是json数组对象
        // console.log(province);
        this.setData({
          provinces: province
        })
        // console.log("page中data的省份：\n", this.data.provinces);
      }
    })
  },
  // 查询城市
  pickCity(id) {
    // let newprovince_id = 'address.province_id';
    let p_id = 'address.province_id';
    let c_id = 'address.city_id';
    let precity_id = this.data.address.city_id;//记录当前城市的id
    if (id) {//如果传了新的省份id过来执行if的代码块
      this.setData({
        [p_id]: id,
      });
      wx.request({
        url: 'https://nideshop.ttxtouring.com/api/region/list?parentId=' + this.data.address.province_id,
        header: {
          "content-type": "application/json",
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: (res) => {
          console.log("城市:\n", res);
          let cities = res.data.data;     //获取到的是json数组对象
          // let newcity_id = 'address.city_id';
          this.setData({
            cities: cities,//给城市数组赋值
          });
          // let currCity = 'address.city_name';
          if (this.data.cities.length > 0) {
            this.setData({
              [c_id]: this.data.cities[0].id,//问题出在这里
              currCity: this.data.cities[0].name
            })
          }
          console.log("当前城市id：", this.data.address.city_id);

          // 记录修改后的城市id
          let currcity_id = this.data.address.city_id;
          //比较两个城市id如果不一样就重新调用查询小区的方法
          if (precity_id != currcity_id) {
            this.pickArea(currcity_id);
          }
        }
      });
    } else {//如果没有传新的省份id过来执行else的代码块
      wx.request({
        url: 'https://nideshop.ttxtouring.com/api/region/list?parentId=' + this.data.address.province_id,
        header: {
          "content-type": "application/json",
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: (res) => {
          console.log("城市:\n", res);
          let cities = res.data.data;     //获取到的是json数组对象
          // let newcity_id = 'address.city_id';
          this.setData({
            cities: cities,//给城市数组赋值
          })
          if (this.data.cities.length > 0) {
            this.setData({
              // [newcity_id]: this.data.cities[0].id,//问题出在这里
              currCity: this.data.cities[0].name
            })
          }
          console.log("当前城市：", this.data.currCity);
          console.log("当前城市id：", this.data.address.city_id);

          // 记录修改后的城市id
          let currcity_id = this.data.address.city_id;
          //比较两个城市id如果不一样就重新调用查询小区的方法
          if (precity_id != currcity_id) {
            this.pickArea(currcity_id);
          }
        }
      });
    }


  },
  // 选择小区
  pickArea(id) {
    let newcity_id = 'address.city_id';
    let currareaid = 'address.district_id';
    if (id) {
      this.setData({
        [newcity_id]: id
      });
      wx.request({
        url: 'https://nideshop.ttxtouring.com/api/region/list?parentId=' + this.data.address.city_id,
        header: {
          "content-type": "application/json",
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: (res) => {
          // console.log("x小区:\n", res);
          let areas = res.data.data;//获取到的是json数组对象
          this.setData({
            areas: areas
          })
          if (this.data.areas.length > 0) {
            this.setData({
              currArea: this.data.areas[0].name,
              [currareaid]: this.data.areas[0].id
            })
          }
          // console.log("当前小区id：",this.data.address.district_id);
        }
      })
    } else {

      wx.request({
        url: 'https://nideshop.ttxtouring.com/api/region/list?parentId=' + this.data.address.city_id,
        header: {
          "content-type": "application/json",
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: (res) => {
          // console.log("x小区:\n", res);
          let areas = res.data.data;//获取到的是json数组对象
          this.setData({
            areas: areas
          })
          if (this.data.areas.length > 0) {
            this.setData({
              currArea: this.data.areas[0].name,
              [currareaid]: this.data.areas[0].id
            })
          }
          // console.log("当前小区id：",this.data.address.district_id);
        }
      })
    }

  },
  //点击省市区输入框触发弹窗
  chooseAdd() {
    this.pickProvince();//获取省份
    // let preprovince_id = 'address.province_id';
    // let precity_id = 'address.city_id';
    // let predistricts_id = 'address.district_id';
    this.setData({
      showDialog: true,
      // [preprovince_id]: 2,
      // [precity_id]: 37,
      // [predistricts_id]: 403,
      // currProvince: '北京市',
      // currCity: '北京市',
      // currArea: '东城区',
    })
    this.pickCity();//获取城市
    this.pickArea();//获取区
  },
  //确认按钮，修改最终省市区的值并关闭弹窗
  changePCA() {
    //先修改省市区的值防止后面获取不到导致无法验证
    let PCA = 'address.full_region';
    this.setData({
      [PCA]: this.data.address.province_name  + this.data.address.city_name  + this.data.address.district_name,
      showDialog: false//关闭弹窗
    });
    // console.log(this.data.address);
  },
  //取消选择省市区按钮，关闭弹窗
  cancelPCA() {
    this.setData({
      showDialog: false
    });
  },


  // 如果是点击地址进来的

  // 获取单个地址
  getOneAdd(id) {
    wx.request({
      url: app.globalData.api.AddressDetail,
      header: {
        "content-type": "application/json",
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      data: {
        id: this.data.address.id
      },
      success: (res) => {
        console.log("单个地址：\n");
        console.log(res);
        this.setData({
          address:res.data.data
        })
      },
    })
  }
})